﻿
using ScFramework.Core;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using UnityEngine;

public class Background : MonoBehaviour
{
    public List<Sprite> sprites = new List<Sprite>();

    public int sortingOrder = -1;
    private List<SpriteRenderer> bgRenders = new List<SpriteRenderer>();
    public Vector2 backgroundScale = Vector2.one * 2f;
    public void UpdateBackground(Vector2 pos, Vector2 ViewSiz, Vector2Int pixel)
    {
        pos = new Vector2(pos.x / backgroundScale.x, pos.y / backgroundScale.y);
        var siz = bgRenders[0].sprite.rect.size;

        int x = 0, y = 0;
        siz.x = siz.x * ViewSiz.x / pixel.x;
        siz.y = siz.y * ViewSiz.y / pixel.y;
        var xv = Mathf.FloorToInt(pos.x / siz.x);
        var yv = Mathf.FloorToInt(pos.y / siz.y);
        if ((xv % 2 + 2) % 2 == 1) x ^= 1;
        if ((yv % 2 + 2) % 2 == 1) y ^= 2;
        pos = new Vector2(pos.x % siz.x, pos.y % siz.y);
        if (pos.x < 0) pos.x += siz.x;
        if (pos.y < 0) pos.y += siz.y;
        Vector3 ans = pos;


        ans.z = 0;
        if (ans.x < siz.x / 2)
        {
            ans.x = -siz.x / 2f - ans.x;
            x ^= 1;
        }
        else ans.x = siz.x / 2f - ans.x;
        if (ans.y < siz.y / 2)
        {
            ans.y = -siz.y / 2f - ans.y;
            y ^= 2;
        }
        else ans.y = siz.y / 2f - ans.y;


        bgRenders[0 ^ x ^ y].transform.localPosition = ans;
        bgRenders[1 ^ x ^ y].transform.localPosition = ans + new Vector3(siz.x, 0, 0);
        bgRenders[2 ^ x ^ y].transform.localPosition = ans + new Vector3(0, siz.y, 0);
        bgRenders[3 ^ x ^ y].transform.localPosition = ans + new Vector3(siz.x, siz.y, 0);

        this.transform.eulerAngles = new Vector3(0, 0, 0);
    }
    public void Awake()
    {
        for (int i = 0; i < 4; i++)
        {
            var obj = new GameObject();
            obj.transform.SetParent(this.transform);
            bgRenders.Add(obj.AddComponent<SpriteRenderer>());
            bgRenders.Last().sprite = sprites[i % sprites.Count];
            bgRenders.Last().sortingOrder = sortingOrder;
            bgRenders.Last().sharedMaterial = Resources.Load<Material>("Mat/SFShadowedSprite");
        }
    }
}
